package com.tbi.graphcolouring.algorithmconfiguration.evaluator;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.tbi.algorithm.configuration.IEvaluator;
import com.tbi.graphcolouring.AlgorithmSettings;
import com.tbi.graphcolouring.BaseGraph;
import com.tbi.graphcolouring.BaseGraph.Node;
import com.tbi.graphcolouring.PopulationEntity;

public class PunishmentEvaluator implements IEvaluator {
	private BaseGraph graph;
	
	public PunishmentEvaluator(BaseGraph graph) {
		this.graph = graph;
	}

	public void setGraph(BaseGraph graph) {
		this.graph = graph;
	}
	
	@Override
	public void evaluate(List<Object> population) {
		for(Object obj : population){
			PopulationEntity entity = (PopulationEntity) obj;
			Set<Integer> colorsSet = new HashSet<>();
			int ratingModifier = 0;
			
//			System.out.println("Unormalized colors: "+Arrays.toString(entity.colors));
			if(AlgorithmSettings.ENABLE_ENTITY_NORMALIZATION){
				normalize(entity.colors);
			}
			graph.setUpColors(entity.colors);
			
			for(Node n : graph.getNodes()){
				colorsSet.add(n.getColor());
				for(Node connectedNode : n.getConnections()){
					if(n.getColor() == connectedNode.getColor()){
						ratingModifier = ratingModifier + AlgorithmSettings.EVALUATION_PUNISHMENT;
					}
				}
			}
			
			entity.rating = colorsSet.size() + ratingModifier;
		}
	}
	
	private void normalize(int[] colors) {
		Map<Integer, Integer> colorMapper = new HashMap<Integer, Integer>();
		for (int i = 0; i < colors.length; i++) {
			if(!colorMapper.containsKey(colors[i])){
				colorMapper.put(colors[i], colorMapper.size());
			}
		}
		for (int i = 0; i < colors.length; i++) {
			colors[i] = colorMapper.get(colors[i]);
		}
//		System.out.println("Normalized colors: "+Arrays.toString(colors));
//		System.out.println("#");
	}

}
